package ma.dev.sowondejong.network;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;

public class PhraseGetRequest extends NetworkRequest {
	
	private final String servAddr = "http://sowondejong.herokuapp.com/phraselist";
	@NotNull
    private ArrayList<String> phraseList = new ArrayList<String>();
	
	public PhraseGetRequest() {
		setUrl(servAddr);	

 	}
	
	@Override
	protected void parsing() {

		setUrl(servAddr);

        try {
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");

			// �����κ��� �޼����� ���� �� �ֵ��� �Ѵ�. 
			conn.setDoInput(true);

			// ������� �����Ѵ�.
			conn.setRequestProperty("Content-Type", "application/json");

			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);

			conn.connect();
			
			InputStream is;
			BufferedReader in;

			is  = conn.getInputStream();
			in  = new BufferedReader(new InputStreamReader(is), 8 * 1024);

			String line;
			JSONArray jArr = new JSONArray();

			while ( ( line = in.readLine() ) != null )
			{
				line.replace("'\'", "");
				jArr.put(line);			
			}

			for(int i = 0; i < jArr.length(); ++i) {
				phraseList.add((String) jArr.get(i));
			}
			
			phraseList.remove( phraseList.size() - 1 );
			phraseList.remove(0);
			
			result = phraseList;
		
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}
}

